<template>
  <div class="score-analysis">
    <!-- 页面背景 -->
    <div class="bg-overlay"></div>

    <el-row class="statistic-section" :gutter="20">
      <!-- 统计信息展示 -->
      <el-col :span="12">
        <el-card class="statistic-card" shadow="hover">
          <div class="card-header">
            <img src="@/assets/images/statics.png" alt="统计图标" class="card-icon"/>
            <h3 class="section-title">考试成绩统计</h3>
          </div>

          <el-tree
            v-model="form.parentId"
            :data="deptOptions"
            :props="treeProps"
            placeholder="选择部门"
            :clearable="false"
            node-key="deptId"
            :expand-on-click-node="false"
            :check-strictly="true"
            @node-click="handleDeptSelect"
            class="dept-tree"
          />

          <div class="statistics-grid">
            <div v-for="(item, index) in examStatistics"
                 :key="index"
                 class="stat-item">
              <div class="stat-label">{{item.name}}</div>
              <div class="stat-value">{{item.value}}</div>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 错误题目统计 -->
      <el-col :span="12">
        <el-card class="statistic-card" shadow="hover">
          <div class="card-header">
            <img src="@/assets/images/error-icon.png" alt="错误题目图标" class="card-icon"/>
            <h3 class="section-title">错题统计(TOP7)</h3>
          </div>
          <el-table
            :data="highErrorRateQuestions"
            border
            stripe
            class="error-table">
            <el-table-column label="题目" prop="question" show-overflow-tooltip></el-table-column>
            <el-table-column label="错题个数" prop="errorCount" width="100" align="center"></el-table-column>
            <el-table-column label="出错率(%)" prop="errorRate" width="100" align="center"></el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加第二行图表展示 -->
    <el-row class="chart-section" :gutter="20">
      <!-- 成绩分布图表 -->
      <el-col :span="12">
        <el-card class="statistic-card" shadow="hover">
          <div class="card-header">
            <img src="@/assets/images/chart-icon.png" alt="图表图标" class="card-icon"/>
            <h3 class="section-title">成绩分布统计</h3>
          </div>
          <div ref="scoreDistChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 错题趋势图表 -->
      <el-col :span="12">
        <el-card class="statistic-card" shadow="hover">
          <div class="card-header">
            <img src="@/assets/images/trend-icon.png" alt="趋势图标" class="card-icon"/>
            <h3 class="section-title">错题趋势分析</h3>
          </div>
          <div ref="errorTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {getStatics,getUserScores,getWrongQuestion,getWrongDailyQuestion} from "@/api/exam/statics";
import Treeselect from "@riophae/vue-treeselect";
import {listDept} from "@/api/system/dept";

export default {
  data() {
    return {
      chartInstance: null,
      // 统计数据
      examStatistics: [],
      // 部门树选项
      deptOptions: [],
      treeProps: {
        label: 'deptName',
        children: 'children'
      },
      // 表单参数
      form: {
        deptId: 100,  // 确保有这个字段
      },

      // 单位排序数据
      selectedUnitType: 'center',
      unitAverageScores: [
        {unitName: '分中心 A', averageScore: '80'},
        {unitName: '分中心 B', averageScore: '75'},
        {unitName: '班组 A', averageScore: '78'},
        {unitName: '班组 B', averageScore: '72'},
      ],
      // 出错率较高的题目数据
      highErrorRateQuestions: [
        // {question: '题目 1', errorRate: '30%'},
        // {question: '题目 2', errorRate: '25%'},
        // {question: '题目 3', errorRate: '22%'},
        // {question: '题目 4', errorRate: '20%'},
        // {question: '题目 5', errorRate: '12%'},
        // {question: '题目 6', errorRate: '10%'},
      ],
      // 新增的数据：成绩分布
      scoreDistributionData: [
        {name: '60-70分', value: 30},
        {name: '70-80分', value: 50},
        {name: '80-90分', value: 15},
        {name: '90-100分', value: 5},
      ],
      // 错误率趋势数据
      errorRateTrendData: [
        {date: '2024-01-01', errorRate: 20},
        {date: '2024-02-01', errorRate: 15},
        {date: '2024-03-01', errorRate: 10},
        {date: '2024-04-01', errorRate: 12},
      ],
      scoreDistChart: null,
      errorTrendChart: null,
    };
  },
  methods: {
    // 可以在这里加入更多的方法来处理数据或请求接口
    getStatics() {
      getStatics(this.form.deptId).then(res => {
        console.log("考试成绩统计",res);
        if (res.code === 200 && res.rows.length > 0) {
          // 处理返回的数据
          const data = res.rows[0];
          this.examStatistics = [
            {name: '参与人数', value: data.participatedUsers},
            {name: '总人数', value: data.totalUsers},
            {name: '最低分', value: data.minScore},
            {name: '最高分', value: data.maxScore},
            //data.avgScore 保留两位小数
            {name: '平均分', value: data.avgScore.toFixed(2)},
            {name: '参与度', value: `${(data.avgParticipation).toFixed(2)}%`},
          ];
          // 更新成绩分布图表
          // this.updateScoreDistChart(data);
          // this.getUsersScores();
        }else {
          this.examStatistics = [
            {name: '参与人数', value: 0},
            {name: '总人数', value: 0},
            {name: '最低分', value: 0},
            {name: '最高分', value:0},
            //data.avgScore 保留两位小数
            {name: '平均分', value: 0},
            {name: '参与度', value: 0},
          ];
        }
      });
      this.getUsersScores();
    },
    getUsersScores() {
      getUserScores(this.form.deptId).then(res => {
        console.log('用户考试成绩分布', res);
        if (res.code === 200 && res.rows.length > 0) {
          const data = res.rows;

          // 初始化成绩分布数据
          const scoreDistributionData = [
            { name: '不及格(0-59分)', value: 0 },
            { name: '及格(60-79分)', value: 0 },
            { name: '良好(80-89分)', value: 0 },
            { name: '优秀(90-100分)', value: 0 }
          ];

          // 统计各分数段的人数
          data.forEach(item => {
            const score = item.userScore;
            if (score < 60) {
              scoreDistributionData[0].value++;
            } else if (score >= 60 && score < 80) {
              scoreDistributionData[1].value++;
            } else if (score >= 80 && score < 90) {
              scoreDistributionData[2].value++;
            } else if (score >= 90) {
              scoreDistributionData[3].value++;
            }
          });

          // 初始化或更新图表
          if (!this.scoreDistChart) {
            this.scoreDistChart = echarts.init(this.$refs.scoreDistChart);
          }

          // 设置图表配置
          const option = {
            tooltip: {
              trigger: 'item',
              formatter: '{b}: {c}人次 ({d}%)'
            },
            legend: {
              orient: 'vertical',
              left: 'left',
              data: scoreDistributionData.map(item => item.name)
            },
            series: [
              {
                name: '成绩分布',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                itemStyle: {
                  borderRadius: 10,
                  borderColor: '#fff',
                  borderWidth: 2
                },
                label: {
                  show: true,
                  position: 'outside',
                  formatter: '{b}\n{c}人次 ({d}%)'
                },
                emphasis: {
                  label: {
                    show: true,
                    fontSize: '16',
                    fontWeight: 'bold'
                  }
                },
                data: [
                  {
                    ...scoreDistributionData[0],
                    itemStyle: { color: '#ee6666' }  // 不及格-红色
                  },
                  {
                    ...scoreDistributionData[1],
                    itemStyle: { color: '#fac858' }  // 及格-黄色
                  },
                  {
                    ...scoreDistributionData[2],
                    itemStyle: { color: '#5470c6' }  // 良好-蓝色
                  },
                  {
                    ...scoreDistributionData[3],
                    itemStyle: { color: '#91cc75' }  // 优秀-绿色
                  }
                ]
              }
            ]
          };

          this.scoreDistChart.setOption(option);
        }
      });
    },
    //错题统计
    getHighErrorRateQuestions() {
      const params = {
        pageNum: 1,
        pageSize: 99999,
      };
      getWrongQuestion(params).then(res => {
        console.log('错题记录',res);
        if (res.code === 200 && res.rows.length > 0) {
          const data = res.rows;

          // 处理错题统计数据
          // const sortedData = data.sort((a, b) => b.wrongCount - a.wrongCount);
          // this.highErrorRateQuestions = sortedData.slice(0, 7).map(item => {
          //   return {
          //     question: item.question?.questionTitle || '<暂无题目>',
          //     errorCount: item.wrongCount,
          //     errorRate: ((item.wrongCount / res.total) * 100).toFixed(2),
          //     lastWrongTime: item.lastWrongTime
          //   };
          // });
          this.highErrorRateQuestions = data.slice(0, 7).map(item => {
              return {
                question: item.questionTitle,
                errorCount: item.totalWrongCount,
                errorRate: (item.wrongProbability * 100).toFixed(2)
              };
            });

          // 按日期分组统计错误次数
          // const dateGroups = {};
          // data.forEach(item => {
          //   const date = item.lastWrongTime;
          //   if (!dateGroups[date]) {
          //     dateGroups[date] = {
          //       wrongCount: 0
          //     };
          //   }
          //   dateGroups[date].wrongCount += item.wrongCount;
          // });

          // 转换为图表所需的数据格式
          // const dates = Object.keys(dateGroups).sort();
          // const errorRates = dates.map(date => {
          //   const group = dateGroups[date];
          //   // 使用总题目数计算错题率
          //   return ((group.wrongCount / res.total) * 100).toFixed(2);
          // });
          //
          // // 更新错题趋势图
          // this.initErrorTrendChart(dates, errorRates);
        }
      });
    },
    getHighErrorAnalysis() {

      getWrongDailyQuestion().then(res => {
        console.log('错题趋势分析',res);
        if (res.code === 200 && res.rows.length > 0) {
          const data = res.rows;

          let dates=[];
          let errorRates=[];
          data.forEach(item => {
            dates.push(item.wrongDate); // 添加日期
            errorRates.push((item.wrongProbability * 100).toFixed(2)); // 百分比（保留两位小数）
          });
          // // 更新错题趋势图
          this.initErrorTrendChart(dates, errorRates);
        }
      });
    },
    getDeptOptions() {
      // 假设这里是异步请求接口获取部门树数据
      listDept().then(response => {
        console.log('获取部门树数据', response);
        this.deptOptions = this.handleTree(response.data, "deptId");
        console.log('处理后的部门树数据', this.deptOptions);
      });
    },
    handleDeptSelect(node) {
      console.log("选择的部门：", node);
      this.form.deptId = node.deptId;
      this.getStatics();
    },
    // 转换部门数据为树形结构
    transformDeptData(data) {
      return data.map(item => {
        return {
          label: item.deptName,
          deptId: item.deptId,
          parentId: item.parentId,
          children: item.children ? this.transformDeptData(item.children) : []
        };
      });
    },
    // 根据deptId查找节点
    findNodeById(treeData, deptId) {
      for (const node of treeData) {
        if (node.deptId === deptId) {
          return node;
        }
        if (node.children) {
          const result = this.findNodeById(node.children, deptId);
          if (result) return result;
        }
      }
      return null;
    },
    initCharts() {
      // 只初始化错题趋势图，成绩分布图会在获取数据后初始化
      this.initErrorTrendChart();
    },

    initErrorTrendChart(dates, errorRates) {
      this.errorTrendChart = echarts.init(this.$refs.errorTrendChart);
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: '{b}<br/>{a}: {c}%'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLabel: {
            rotate: 45,
            formatter: (value) => {
              return value.split(' ')[0]; // 只显示日期部分
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: '{value}%'
          },
          min: 0,
          max: 100
        },
        series: [
          {
            name: '当日错题占比',
            type: 'line',
            smooth: true,
            data: errorRates,
            areaStyle: {
              opacity: 0.3,
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(64,158,255,0.5)' },
                { offset: 1, color: 'rgba(64,158,255,0.1)' }
              ])
            },
            itemStyle: {
              color: '#409EFF'
            },
            emphasis: {
              focus: 'series',
              itemStyle: {
                borderWidth: 2
              }
            },
            markPoint: {
              data: [
                { type: 'max', name: '最大值' },
                { type: 'min', name: '最小值' }
              ]
            }
          }
        ]
      };
      this.errorTrendChart.setOption(option);
    },

    handleResize() {
      this.scoreDistChart && this.scoreDistChart.resize();
      this.errorTrendChart && this.errorTrendChart.resize();
    },
  },
  components: {Treeselect},
  mounted() {
    this.$nextTick(() => {
      this.initCharts();
      window.addEventListener('resize', this.handleResize);
    });
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize);
    this.scoreDistChart && this.scoreDistChart.dispose();
    this.errorTrendChart && this.errorTrendChart.dispose();
  },
  created() {
    this.getStatics();
    this.getDeptOptions();
    this.getHighErrorRateQuestions();
    this.getHighErrorAnalysis();
  }
};
</script>

<style scoped>
.score-analysis {
  padding: 20px;
  min-height: 100vh;
  position: relative;
}

.bg-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.8)),
              url("../assets/images/background.jpg");
  background-size: cover;
  background-position: center;
  z-index: -1;
}

.statistic-section {
  position: relative;
  z-index: 1;
}

.statistic-card {
  border-radius: 15px;
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  transition: all 0.3s ease;
}

.statistic-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 15px 0;
  border-bottom: 2px solid #f0f2f5;
  margin-bottom: 20px;
}

.card-icon {
  width: 32px;
  height: 32px;
  margin-right: 12px;
}

.section-title {
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
  margin: 0;
}

.dept-tree {
  margin: 15px 0;
  border-radius: 8px;
  padding: 10px;
  background: #f8f9fa;
}

.statistics-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
  padding: 15px 0;
}

.stat-item {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 10px;
  text-align: center;
}

.stat-label {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
}

.stat-value {
  color: #409EFF;
  font-size: 20px;
  font-weight: bold;
}

.error-table {
  margin-top: 15px;
}

.error-table :deep(.el-table__header) {
  background-color: #f5f7fa;
}

.error-table :deep(.el-table__row) {
  transition: all 0.3s ease;
}

.error-table :deep(.el-table__row:hover) {
  background-color: #ecf5ff !important;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .statistics-grid {
    grid-template-columns: 1fr;
  }

  .el-col {
    width: 100% !important;
  }
}

.chart-section {
  margin-top: 20px;
}

.chart-container {
  height: 400px;
  width: 100%;
  margin-top: 20px;
}
</style>
